using MediatR;
using Microsoft.AspNetCore.Mvc;
using STD.Shared.Contracts.DTOs;
using STD.Services.UserService.Application.Commands;
using STD.Services.UserService.Application.Queries;
using STD.Services.UserService.Domain.Entities;

namespace STD.Services.UserService.Presentation.Controllers;

/// <summary>
/// 用户控制器
/// </summary>
[ApiController]
[Route("api/[controller]")]
public class UsersController : ControllerBase
{
    private readonly IMediator _mediator;
    
    public UsersController(IMediator mediator)
    {
        _mediator = mediator;
    }
    
    /// <summary>
    /// 获取所有用户
    /// </summary>
    /// <param name="skip">跳过数量</param>
    /// <param name="take">获取数量</param>
    /// <returns>用户列表</returns>
    [HttpGet]
    public async Task<ActionResult<ApiResponse<IEnumerable<User>>>> GetUsers(
        [FromQuery] int skip = 0, 
        [FromQuery] int take = 100)
    {
        var query = new GetAllUsersQuery { Skip = skip, Take = take };
        var result = await _mediator.Send(query);
        
        if (!result.IsSuccess)
        {
            return BadRequest(ApiResponse<IEnumerable<User>>.FailureResult(result.ErrorMessage!));
        }
        
        return Ok(ApiResponse<IEnumerable<User>>.SuccessResult(result.Data!));
    }
    
    /// <summary>
    /// 根据ID获取用户
    /// </summary>
    /// <param name="id">用户ID</param>
    /// <returns>用户信息</returns>
    [HttpGet("{id}")]
    public async Task<ActionResult<ApiResponse<User>>> GetUser(Guid id)
    {
        var query = new GetUserQuery { Id = id };
        var result = await _mediator.Send(query);
        
        if (!result.IsSuccess)
        {
            return NotFound(ApiResponse<User>.FailureResult(result.ErrorMessage!));
        }
        
        return Ok(ApiResponse<User>.SuccessResult(result.Data!));
    }
    
    /// <summary>
    /// 创建用户
    /// </summary>
    /// <param name="command">创建用户命令</param>
    /// <returns>创建的用户</returns>
    [HttpPost]
    public async Task<ActionResult<ApiResponse<User>>> CreateUser([FromBody] CreateUserCommand command)
    {
        var result = await _mediator.Send(command);
        
        if (!result.IsSuccess)
        {
            return BadRequest(ApiResponse<User>.FailureResult(result.ErrorMessage!));
        }
        
        return CreatedAtAction(
            nameof(GetUser), 
            new { id = result.Data!.Id }, 
            ApiResponse<User>.SuccessResult(result.Data));
    }
    
    /// <summary>
    /// 健康检查
    /// </summary>
    /// <returns>健康状态</returns>
    [HttpGet("health")]
    public ActionResult<ApiResponse<string>> Health()
    {
        return Ok(ApiResponse<string>.SuccessResult("UserService is healthy"));
    }
} 